package com.ztgf.pay.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.trz.netwk.api.system.TrdMessenger;
import com.trz.netwk.api.trd.*;
import com.trz.netwk.api.vo.*;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.BigDecimalUtils;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.order.models.dto.OrderInfoDTO;
import com.ztgf.order.models.dto.OrderReturnCommodityDTO;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.IOrderReturnCommodityService;
import com.ztgf.pay.async.IAsyncService;
import com.ztgf.pay.common.config.YmlConfig;
import com.ztgf.pay.common.service.IPayCommonService;
import com.ztgf.pay.mapper.PayOrderMapper;
import com.ztgf.pay.models.bo.PayBatchByRemarksBO;
import com.ztgf.pay.models.bo.PayBatchPrintBO;
import com.ztgf.pay.models.bo.PayOrderMotherSaveBO;
import com.ztgf.pay.models.dto.PayHttpLogDTO;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.pay.models.dto.PayOrderMotherDTO;
import com.ztgf.pay.models.dto.PayUserDTO;
import com.ztgf.pay.models.service.*;
import com.ztgf.pay.models.vo.OrderReceiptQuantityVO;
import com.ztgf.pay.models.vo.PayBatchPrintVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 支付订单控制器
 *
 * @author mxli
 * @Date 2020-07-30 12:12:21
 */
@DubboService
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrderDTO> implements IPayOrderService{

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private IPayUserService payUserService;
    @Autowired
    private IPayHttpLogService httpLogService;
    @Autowired
    private IPayOrderMotherService payOrderMotherService;
    @Autowired
    private IAsyncService asyncService;
    @Autowired
    private IPayOrderRepayService payOrderRepayService;
    @DubboReference
    private IOrderInfoService orderInfoService;
    @DubboReference
    private IOrderReturnCommodityService orderReturnCommodityService;
    @Autowired
    private IPayCommonService payCommonService;

    @Value("${zj-pay.page-pay-url-wallet}")
    private String pageWalletUrl; //我的钱包
    @Value("${zj-pay.page-pay-url-margin}")
    private String pageMarginUrl; //保证金
    @Value("${zj-pay.page-pay-url-annual-fee}")
    private String pageAnnualFeeUrl; //年费
    @Value("${zj-pay.page-pay-url-order}")
    private String pageOrderUrl; //订单支付成功
    @Value("${zj-pay.notice-url}")
    private String noticeUrl;//后台地址

    @Value("${ztgf-income-user-id}")
    private Long ztgfIncomeUserId;//中铁工服收益账号

    /**
     * 网银支付
     * @param saveBO
     * @return
     */
    @Override
    public Result<PayOrderMotherDTO> saveOnlineBankPay(PayOrderMotherSaveBO saveBO) {
        if(saveBO.getPaymentUserId() == null || saveBO.getBankId() == null || saveBO.getMoney() == null || saveBO.getMoney().doubleValue() <= 0
            || StrUtils.isEmpty(saveBO.getBankName()) || StrUtils.isEmpty(saveBO.getChildOrderList())){
            return new Result(CodeEnum.FAIL_100002);
        }

        List<PayOrderDTO> orderDTOS = JSON.parseArray(saveBO.getChildOrderList(), PayOrderDTO.class);
        if(orderDTOS == null || orderDTOS.size() == 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        PayUserDTO dto = payUserService.getPayUserDTO(saveBO.getPaymentUserId());
        if(dto == null){
            return new Result(CodeEnum.FAIL_200003);
        }
        //添加请求日志
        Long motherId = ymlConfig.getPkId();
        PayHttpLogDTO logDTO = new PayHttpLogDTO();

        PayOrderMotherDTO motherDTO = new PayOrderMotherDTO();
        motherDTO.setId(motherId);
        Result<PayOrderMotherDTO> result = new Result<>();
        try {
            List<SplitFundBillInfo> billInfolist = new ArrayList<SplitFundBillInfo>();
            savePayOnlineBankParams(saveBO, dto, motherDTO, orderDTOS, billInfolist);
            result = httpclientPayOnlineBank(saveBO, motherDTO, billInfolist, logDTO);
            if(result.success()){
                result.setData(motherDTO);
            } else {
                result.setCode(result.getCode());
                result.setMsg(result.getMsg());
                motherDTO.setStatus(3);//状态 0创建中、1支付中、2成功、3失败、4过期
            }

        } catch (Exception e) {
            log.error("TrdT4501Request 网银支付 is error", e);
            if(e instanceof ServiceException){
                result.setCode(((ServiceException) e).getCode());
                result.setMsg(e.getMessage());
            } else {
                result = new Result<>(CodeEnum.FAIL_200022);
            }
            logDTO.setStatus(1);
            logDTO.setReturnValue("TrdT4501Request 网银支付 500");
            motherDTO.setStatus(3);//状态 0创建中、1支付中、2成功、3失败、4过期
        }

        //添加日志
        logDTO.setId(ymlConfig.getPkId());
        httpLogService.insert(logDTO);
        payOrderMotherService.updateById(motherDTO);
        return result;
    }


    /**
     * 余额支付
     * @param saveBO
     * @return
     */
    @Override
    public Result<List<PayOrderDTO>> saveBalancePay(PayOrderMotherSaveBO saveBO) {

        log.error("------------saveBalancePay----->>>>>>>"+JSON.toJSONString(saveBO));

//        if(saveBO.getPaymentUserId() == null || saveBO.getMoney() == null || saveBO.getMoney().doubleValue() <= 0 || StrUtils.isEmpty(saveBO.getChildOrderList())){
        if(saveBO.getMoney() == null || saveBO.getMoney().doubleValue() <= 0 || StrUtils.isEmpty(saveBO.getChildOrderList())){
            return new Result(CodeEnum.FAIL_100002);
        }
        List<PayOrderDTO> orderDTOS = JSON.parseArray(saveBO.getChildOrderList(), PayOrderDTO.class);
        if(orderDTOS == null || orderDTOS.size() == 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        PayUserDTO dto = payUserService.getPayUserDTO(saveBO.getPaymentUserId());
        if(dto == null){
            return new Result(CodeEnum.FAIL_200003);
        }

        //调用余额接口
        PayOrderMotherDTO motherDTO = new PayOrderMotherDTO();
        //添加请求日志
        PayHttpLogDTO logDTO = new PayHttpLogDTO();
        Result<List<PayOrderDTO>> result = new Result<>();
        int status = 3;
        try {
            //组装参数
            List<PayInfo> payInfoList = new ArrayList<PayInfo>();
            Map<String , PayOrderDTO> orderDTOMap = new HashMap<>();
            savePayBalanceParams(saveBO, dto, motherDTO, orderDTOS, payInfoList, orderDTOMap);
            Result<List<PayRsut>> httpResult =  httpclientPayBalance(payInfoList, logDTO);
            if(httpResult.success()){
                status = 2;
                result.setData(orderDTOS);
            } else {
                result.setCode(httpResult.getCode());
                result.setMsg(httpResult.getMsg());
            }
            logDTO.setWaterId(motherDTO.getId());
            payCommonService.savePayBalanceResult(httpResult.getData(), orderDTOMap);
        } catch (Exception e) {
            log.error("TrdT3005Request 余额支付 is error", e);
            if(e instanceof ServiceException){
                result.setCode(((ServiceException) e).getCode());
                result.setMsg(e.getMessage());
            } else {
                result = new Result<>(CodeEnum.FAIL_200022);
            }
            logDTO.setStatus(1);
            logDTO.setReturnValue("TrdT3005Request 余额支付 500");

        }

        //添加日志
        logDTO.setId(ymlConfig.getPkId());
        httpLogService.insert(logDTO);
        PayOrderMotherDTO newMotherDTO = new PayOrderMotherDTO();
        newMotherDTO.setId(motherDTO.getId());
        newMotherDTO.setStatus(status);
        payOrderMotherService.updateById(newMotherDTO);
        return result;
    }


    /**
     * 保存查询网银支付状态
     * @param motherDTO
     */
    @Override
    @Transactional
    public void saveOnlineBankPayLog(PayOrderMotherDTO motherDTO) {
        if(motherDTO == null){
            return;
        }
        //查询子订单
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("mother_order_id", motherDTO.getId());
        List<PayOrderDTO> orderDTOS = this.selectList(wrapper);
        if(orderDTOS == null || orderDTOS.size() == 0){
            //不做处理 return;
            throw new ServiceException(CodeEnum.FAIL.getCode(), "PayOrderDTO 查询网银支付状态 orderDTOS is null : " + motherDTO.getId());
        }

        TrdT4504Response trdResponse = getTrdT4504Response(motherDTO.getId());
        if(trdResponse == null){
            throw new ServiceException(CodeEnum.FAIL.getCode(), "PayOrderDTO 查询网银支付状态 orderDTOS is null : " + motherDTO.getId());
        }
        int status = 0;
        if ("000000".equals(trdResponse.getMsghd_rspcode())) {
//
//                List<SplitFundBillInfo> billInfoList=trdResponse.getBillinfoList();
//                if (null != billInfoList && !billInfoList.isEmpty()) {
//                    System.out.println("================================================");
//                    System.out.println("AclAmt"+trdResponse.getAmt_aclamt());
//                    System.out.println("CcyCd"+trdResponse.getAmt_ccycd());
//                    System.out.println("[Merchantid]=[" + trdResponse.getMerchantid() + "]"); // 终端商户号
//                    for (SplitFundBillInfo splitFundBillInfo : billInfoList) {
//                        System.out.println("RSubNo:"+splitFundBillInfo.getBillinfo_rsubno());
//                        System.out.println("RCltNm:"+splitFundBillInfo.getBillinfo_rcltnm());
//                        System.out.println("BillNo:"+splitFundBillInfo.getBillinfo_billno());
//                        System.out.println("OrderNo:"+splitFundBillInfo.getBillinfo_orderno());
//                        System.out.println("RSubNo:"+splitFundBillInfo.getBillinfo_aclamt());
//                        System.out.println("BillAmt:"+splitFundBillInfo.getBillinfo_billamt());
//                        System.out.println("AclAmt:"+splitFundBillInfo.getBillinfo_aclamt());
//                        System.out.println("CcyCd:"+splitFundBillInfo.getBillinfo_ccycd());
//                        System.out.println("Usage:"+splitFundBillInfo.getBillinfo_usage());
//                        System.out.println("TrsFlag:"+splitFundBillInfo.getBillinfo_trsflag());
//                    }
//
//                }
            if("1".equals(trdResponse.getState())){
                status = 2;
            } else if("2".equals(trdResponse.getState())){
                status = 3;
                motherDTO.setZjFailMsg(trdResponse.getOpion());
            } else {
                return;
            }


        } else {
            // ！！！ 在这里添加合作方处理逻辑！！！ 修改失败
            status = 3;
            motherDTO.setZjFailMsg(trdResponse.getMsghd_rspmsg());
        }

        //处理子订单
        for (PayOrderDTO orderDTO : orderDTOS) {
            orderDTO.setStatus(status);
            orderDTO.setZjFailMsg(motherDTO.getZjFailMsg());
            int revision = orderDTO.getRevision();
            wrapper = new EntityWrapper();
            wrapper.eq("id", orderDTO.getId());
            wrapper.eq("revision", revision);
            orderDTO.setRevision(revision + 1);
            if(!this.update(orderDTO, wrapper)){
                throw new ServiceException(CodeEnum.FAIL.getCode(), "修改子订单错误 : " + orderDTO.getId());
            }
            if(status == 2){
                //处理不可提现余额
                payCommonService.saveNoWithdrawMoney(orderDTO.getPaymentUserId());
            }
            //处理回调，事务提交后处理
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    try{
                        asyncService.notifyPayOrder(orderDTO);
                    } catch (ServiceException e) {
                        log.error("修改savePayOrderLogDTOStatus", e);
                    }
                }
            });

        }

        motherDTO.setStatus(status);
        motherDTO.setNotifyStatus(1);

        wrapper = new EntityWrapper();
        int revision = motherDTO.getRevision();
        wrapper.eq("id", motherDTO.getId());
        wrapper.eq("revision", revision);
        motherDTO.setRevision(revision + 1);
        if(!payOrderMotherService.update(motherDTO, wrapper)){
            throw new ServiceException(CodeEnum.FAIL.getCode(), "修改母订单错误: " + motherDTO.getId());
        }
    }

    /**
     * 保存查询余额支付状态
     * @param orderDTO
     */
    @Override
    @Transactional
    public void saveBalancePayLog(PayOrderDTO orderDTO) {
        if(orderDTO == null){
            return;
        }
        TrdT3006Response trdResponse = getTrdT3006Response(orderDTO.getId());
        if(trdResponse == null){
            throw new ServiceException(CodeEnum.FAIL.getCode(), "TrdT3006Request 查询余额支付状态 trdResponse is null : " + orderDTO.getId());
        }
        // 交易成功 000000
        int status = 0;
        if ("000000".equals(trdResponse.getMsghd_rspcode())) {
            // ！！！ 在这里添加合作方处理逻辑！！！
            System.out.println("[msghd_rspmsg]=[" + trdResponse.getMsghd_rspmsg() + "]"); // 返回信息
            System.out.println("[srl_ptnsrl]=[" + trdResponse.getSrl_ptnsrl() + "]"); // 合作方流水号
            System.out.println("[srl_platsrl]=[" + trdResponse.getSrl_platsrl() + "]"); // 平台流水号
            System.out.println("[billinfo_billno]=[" + trdResponse.getBillinfo_billno() + "]"); // 支付单号(唯一)
            System.out.println("[billinfo_platsrl]=[" + trdResponse.getBillinfo_platsrl() + "]"); // 平台交易流水号
            System.out.println("[billinfo_billstate]=[" + trdResponse.getBillinfo_billstate() + "]"); // 交易结果:0失败;1成功;2处理中
            System.out.println("[billinfo_billstate]=[" + trdResponse.getBillinfo_opion() + "]"); // 失败原因


            if("1".equals(trdResponse.getBillinfo_billstate())){
                status = 2;
            } else if("2".equals(trdResponse.getBillinfo_billstate())){
                status = 3;
                orderDTO.setZjFailMsg(trdResponse.getBillinfo_opion());
            } else {
                return;
            }

        } else {
            status = 3;
            orderDTO.setZjFailMsg(trdResponse.getMsghd_rspmsg());
        }

        orderDTO.setStatus(status);
        orderDTO.setNotifyStatus(1);
        int revision = orderDTO.getRevision();
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", orderDTO.getId());
        wrapper.eq("revision", revision);
        orderDTO.setRevision(revision + 1);
        if(!this.update(orderDTO, wrapper)){
            throw new ServiceException(CodeEnum.FAIL.getCode(), "修改订单错误 : " + orderDTO.getId());
        }
        //处理回调，事务提交后处理
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
            try{
                asyncService.notifyPayOrder(orderDTO);
            } catch (ServiceException e) {
                log.error("修改savePayOrderLogDTOStatus", e);
            }
            }
        });

    }

    @Override
    public Result<String> getOnlineBankPayLog(Long motherId) {
        TrdT4504Response trdResponse = getTrdT4504Response(motherId);
        if(trdResponse == null){
            return new Result<>(CodeEnum.FAIL);
        } else {
            return new Result<>(trdResponse.getResponsePlainText());
        }
    }

    private TrdT4504Response getTrdT4504Response(Long motherId){
        TrdT4504Response  trdResponse = null;
        try {
            // 2. 实例化交易对象
            TrdT4504Request trdRequest = new TrdT4504Request();
            /**
             * 2 实例化交易对象
             */
            trdRequest.setMsghd_trdt(DateUtils.dateToStr(new Date(),DateUtils.DATE_FORMAT_DATESHORTDAY));// 交易日期
            trdRequest.setSrl_ptnsrl(motherId.toString());// 合作方交易流水号
            /**
             * 3.报文处理
             */
            trdRequest.process();
            System.out.println("请求报文[" + trdRequest.getRequestPlainText() + "]");
            System.out.println("签名原文[" + trdRequest.getRequestMessage() + "]");
            System.out.println("签名数据[" + trdRequest.getRequestSignature() + "]");

            /**
             * 4 和融资平台通信
             */
            TrdMessenger trdMessenger = new TrdMessenger();
            // responseMessage
            String respMsg = trdMessenger.send(trdRequest);
            trdResponse = new TrdT4504Response(respMsg);
            log.info("请求报文[" + trdRequest.getRequestPlainText() + "]" + "/n 响应报文[" + trdResponse.getResponsePlainText() + "]");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TrdT4504Request 查询网银支付状态 is error", e);
        }
        return trdResponse;
    }



    @Override
    public Result<String> getBalancePayLog(Long orderId) {
        TrdT3006Response trdResponse = getTrdT3006Response(orderId);
        if(trdResponse == null){
            return new Result<>(CodeEnum.FAIL);
        } else {
            return new Result<>(trdResponse.getResponsePlainText());
        }
    }

    private TrdT3006Response getTrdT3006Response(Long orderId) {
        TrdT3006Response trdResponse = null;
        try {
            // 2. 实例化交易对象
            TrdT3006Request trdRequest = new TrdT3006Request();
            trdRequest.setMsghd_trdt(DateUtils.dateToStr(new Date(),DateUtils.DATE_FORMAT_DATESHORTDAY));
            trdRequest.setBillno(orderId.toString());

            // 3. 报文处理
            trdRequest.process();
            System.out.println("请求报文[" + trdRequest.getRequestPlainText() + "]");
            System.out.println("签名原文[" + trdRequest.getRequestMessage() + "]");
            System.out.println("签名数据[" + trdRequest.getRequestSignature() + "]");

            // 4. 与融资平台通信
            TrdMessenger trdMessenger = new TrdMessenger();
            // message
            String respMsg = trdMessenger.send(trdRequest);

            // 5. 处理交易结果
            trdResponse = new TrdT3006Response(respMsg);
            System.out.println("响应报文[" + trdResponse.getResponsePlainText() + "]");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TrdT4504Request 查询余额支付状态 is error", e);
        }
        return trdResponse;
    }


    @Override
    public List<String> printingElectronicReceipt(String orderId,String userId, String date) {
        List<String> urls = new ArrayList<>();
        //账户类型( 1:客户资金账户 3:合作方收益账户 4:手续费账户)
        PayUserDTO dto = payUserService.getPayUserDTO(Long.parseLong(userId), 1);
        if (dto == null) {
            return urls;
        }

        //售后处理
        List<PayBatchPrintBO> payBatchPrintBOList = new ArrayList<>();
        PayBatchPrintBO payBatchPrintBO2 = new PayBatchPrintBO();
        payBatchPrintBO2.setOrderId(orderId);
        payBatchPrintBO2.setShopId(userId);
        payBatchPrintBO2.setType(1);
        payBatchPrintBOList.add(payBatchPrintBO2);
        EntityWrapper<OrderInfoDTO> orderInfoDTOEntityWrapper = new EntityWrapper<>();
        orderInfoDTOEntityWrapper.eq("order_no",orderId);
        OrderInfoDTO orderInfoDTO = orderInfoService.selectOne(orderInfoDTOEntityWrapper);
        EntityWrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id",orderInfoDTO.getId());
        wrapper.eq("after_sales_state",3);
        List<OrderReturnCommodityDTO> orderReturnCommodityDTOList = orderReturnCommodityService.selectList(wrapper);
        if (orderReturnCommodityDTOList!=null && orderReturnCommodityDTOList.size()>0){
            for (OrderReturnCommodityDTO orderReturnCommodityDTO : orderReturnCommodityDTOList) {
                PayBatchPrintBO payBatchPrintBO1 = new PayBatchPrintBO();
                payBatchPrintBO1.setShopId(userId);
                payBatchPrintBO1.setType(0);
                payBatchPrintBO1.setOrderId(String.valueOf(orderReturnCommodityDTO.getId()));
                payBatchPrintBOList.add(payBatchPrintBO1);
            }
        }
        for (PayBatchPrintBO payBatchPrintBO : payBatchPrintBOList) {
            Date beginDate = DateUtils.strToDate(date, DateUtils.DATE_FORMAT_DATETIME);
            //增加十年查询回单
            Date endDate = DateUtils.addYear(beginDate,10);
            String dateStr = DateUtils.dateToStr(beginDate, DateUtils.DATE_FORMAT_DATESHORTDAY);
            String endDateStr = DateUtils.dateToStr(endDate, DateUtils.DATE_FORMAT_DATESHORTDAY);

            TrdT2014Request request2014 = new TrdT2014Request();
            request2014.setMsghd_trdt(dateStr);
            request2014.setCltacc_subno(dto.getZjMoneyNo());
            request2014.setQuystdt(dateStr);
            request2014.setQuyenddt(endDateStr);
            //pageBeginNum
            request2014.setStartnum("1");
            //备注通过orderId过滤转账记录凭证
            request2014.setQptnusg(payBatchPrintBO.getOrderId());
            TrdMessenger trdMessenger = new TrdMessenger();
            try {
                request2014.process();
                String send = trdMessenger.send(request2014);
                log.info("TrdT2014请求明文：" + request2014.getRequestPlainText());
                TrdT2014Response trdT2014Response = new TrdT2014Response(send);
                List<QuyDaT2014> quyDatList = trdT2014Response.getQuyDatList();
                log.info("trdT2014Response电子转账凭证:" + JSON.toJSONString(quyDatList));
                if (quyDatList != null && !quyDatList.isEmpty()) {
                    for (int i = 0; i < quyDatList.size(); i++) {
                        QuyDaT2014 quyDaT2014 = quyDatList.get(i);
                        TrdT2019Request trdT2019Request = new TrdT2019Request();
                        trdT2019Request.setQuyda_verifycode(quyDaT2014.getVerifycode());
                        trdT2019Request.setSrl_ptnsrl(payBatchPrintBO.getOrderId());
                        trdT2019Request.setQuyda_billno(quyDaT2014.getBillno());
                        trdT2019Request.setQuyda_bnkvid(quyDaT2014.getBnkvid());
                        trdT2019Request.setMsghd_trdt(dateStr);
                        trdT2019Request.setQuyda_dte(dateStr);
                        trdT2019Request.setQuyda_subno(dto.getZjMoneyNo());
                        trdT2019Request.process();
                        log.info("trdT2019请求明文：" + trdT2019Request.getRequestPlainText());
                        String response2019 = trdMessenger.send(trdT2019Request);
                        TrdT2019Response trdT2019Response = new TrdT2019Response(response2019);
                        log.info("trdT2019响应结果：" + trdT2019Response == null ? "" : trdT2019Response.getPdffile());
                        String pdffile = trdT2019Response.getPdffile();
                        if (!StrUtils.isEmpty(pdffile)) {
                            byte[] decode = Base64.getDecoder().decode(pdffile);
                            pdffile = new String(decode);
                            log.info("trdT2019响应结果,base64解码后：" + pdffile);
                            urls.add(pdffile);
                        }
                    }

                }
            } catch (Exception e) {
                log.error("printing electronic receipt error. message is {}", e.getMessage());
                e.printStackTrace();
            }
        }

        return urls;
    }


    @Transactional(rollbackFor = ServiceException.class)
    public void savePayBalanceParams(PayOrderMotherSaveBO saveBO, PayUserDTO payUserDTO, PayOrderMotherDTO motherDTO, List<PayOrderDTO> orderDTOS, List<PayInfo> payInfoList, Map<String, PayOrderDTO> orderDTOMap){
        motherDTO.setId(ymlConfig.getPkId());
        motherDTO.setPaymentUserId(payUserDTO.getUserId());//付款方id
        motherDTO.setPaymentUserName(payUserDTO.getUserName());//付款方名称
        motherDTO.setPaymentUserNo(payUserDTO.getZjMoneyNo());//付款方账号
        motherDTO.setBankId(saveBO.getBankId());//银行id
        motherDTO.setBankName(payUserDTO.getZjBankName());//银行名称
        motherDTO.setMoney(saveBO.getMoney());//付款金额
        motherDTO.setType(0);//类型 0余额、1网银
        motherDTO.setStatus(0);//状态 0创建中、1支付中、2成功、3失败、4过期
        motherDTO.setExpiredTime(DateUtils.addMinute(new Date(), 60));
        motherDTO.setNotifyUrl(saveBO.getNotifyUrl());
        motherDTO.setNotifyPageUrl(saveBO.getNotifyPageUrl());
        BigDecimal total = BigDecimalUtils.getBigDecimal(0);
        // 批量支付数据
        for (PayOrderDTO orderDTO : orderDTOS){

            if(StrUtils.isEmpty(orderDTO.getBusinessOrderWaterNo()) || orderDTO.getBusinessType() == null || StrUtils.isEmpty(orderDTO.getTrsFlag())){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            PayUserDTO userDTO = payUserService.getPayUserDTO(orderDTO.getReceiveUserId());
            if(userDTO == null){
                throw new ServiceException(CodeEnum.FAIL_200003);
            }

            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("status", 2);
            wrapper.eq("business_order_water_no", orderDTO.getBusinessOrderWaterNo());
            PayOrderDTO successDto = this.selectOne(wrapper);
            if(successDto != null){
                throw new ServiceException(CodeEnum.FAIL_200023);
            }

            orderDTO.setId(ymlConfig.getPkId());
            orderDTO.setPaymentUserId(motherDTO.getPaymentUserId());
            orderDTO.setPaymentUserName(motherDTO.getPaymentUserName());
            orderDTO.setPaymentUserNo(motherDTO.getPaymentUserNo());
            orderDTO.setReceiveUserId(userDTO.getUserId());
            orderDTO.setReceiveUserName(userDTO.getUserName());
            orderDTO.setReceiveUserNo(userDTO.getZjMoneyNo());
            orderDTO.setStatus(0);
            orderDTO.setType(0);
            orderDTO.setMotherOrderId(motherDTO.getId());
            orderDTO.setNotifyUrl(saveBO.getNotifyUrl());

            total = BigDecimalUtils.add(total, orderDTO.getMoney());

            PayInfo payInfo = new PayInfo();
            payInfo.setPsubno(orderDTO.getPaymentUserNo());/** 付款方资金账号 */
            payInfo.setPnm(orderDTO.getPaymentUserName());/** 付款方账户名称 */
            payInfo.setRsubno(orderDTO.getReceiveUserNo());/** 收款方资金账号 */
            payInfo.setRcltnm(orderDTO.getReceiveUserName());/** 收款方账户名称 */
            payInfo.setOrderno(orderDTO.getBusinessOrderNo());/** 业务单号 */
            payInfo.setBillno(orderDTO.getId().toString());/** 支付流水号(唯一) */
            payInfo.setAclamt(BigDecimalUtils.multiply(orderDTO.getMoney(), 100).longValue());/** 本次支付金额 */
//                payInfo.setPayfee(billinfo_payfee);/** 付款方手续费,暂定0 */
//                payInfo.setPayeefee(billinfo_payeefee);/** 收款方手续费,暂定0 */
            payInfo.setUsage(orderDTO.getMoneyUsage()+"-"+orderDTO.getId());/** 资金用途(附言) */

            if(StrUtils.isEmpty(orderDTO.getTrsFlag())){
                orderDTO.setTrsFlag(saveBO.getTrsFlag());
            }

            /**
             * A00 普通订单支付 <br>
             * B00 收款方收款成功后，再冻结资金 <br>
             * B01 付款方解冻资金后，再支付给收款方
             */
            payInfo.setTrsflag(orderDTO.getTrsFlag());
            payInfoList.add(payInfo);
            orderDTOMap.put(orderDTO.getId().toString(), orderDTO);

        }

        if(total.compareTo(motherDTO.getMoney()) != 0){
            throw new ServiceException(CodeEnum.FAIL_200025);
        }
        payOrderMotherService.insert(motherDTO);
        this.insertBatch(orderDTOS);
    }


    public Result<List<PayRsut>> httpclientPayBalance(List<PayInfo> payInfoList, PayHttpLogDTO logDTO) throws Exception {
        // 2. 实例化交易对象
        TrdT3005Request trdRequest = new TrdT3005Request();
        trdRequest.setMsghd_trdt(DateUtils.dateToStr(new Date(),DateUtils.DATE_FORMAT_DATESHORTDAY));/** 交易日期 */
        trdRequest.setPayInfoList(payInfoList);
        // 3. 报文处理
        trdRequest.process();

        logDTO.setParams(trdRequest.getRequestPlainText());
        // 4. 与融资平台通信
        TrdMessenger trdMessenger = new TrdMessenger();
        // message
        String respMsg = trdMessenger.send(trdRequest);
        // 5. 处理交易结果
        TrdT3005Response trdResponse = new TrdT3005Response(respMsg);
//            System.out.println("响应报文[" + trdResponse.getResponsePlainText() + "]");

        logDTO.setReturnValue(trdResponse.getResponsePlainText());
        logDTO.setBusinessStatus(trdResponse.getMsghd_rspcode());
        logDTO.setBusinessNotes(trdResponse.getMsghd_rspmsg());
        logDTO.setParams(trdRequest.getRequestPlainText());
        logDTO.setStatus(0);
        log.info("请求报文[" + trdRequest.getRequestPlainText() + "]" + "/n 响应报文[" + trdResponse.getResponsePlainText() + "]");
        // 交易成功 000000
        if ("000000".equals(trdResponse.getMsghd_rspcode())) {
            // ！！！ 在这里添加合作方处理逻辑！！！
//                System.out.println("[msghd_rspmsg]=[" + trdResponse.getMsghd_rspmsg() + "]"); // 返回信息
//                System.out.println("[payRsutList.size]=[" + trdResponse.getPayRsutList().size() + "]"); // 支付数量
            List<PayRsut> payRsutList = trdResponse.getPayRsutList();
            return new Result<>(payRsutList);
        } else {
            return new Result(CodeEnum.FAIL_200022.getCode(), trdResponse.getMsghd_rspmsg());
        }
    }


    @Transactional(rollbackFor = ServiceException.class)
    public void savePayOnlineBankParams(PayOrderMotherSaveBO saveBO, PayUserDTO payUserDTO, PayOrderMotherDTO motherDTO, List<PayOrderDTO> orderDTOS, List<SplitFundBillInfo> billInfolist){
        motherDTO.setPaymentUserId(payUserDTO.getUserId());//付款方id
        motherDTO.setPaymentUserName(payUserDTO.getUserName());//付款方名称
        motherDTO.setPaymentUserNo(payUserDTO.getZjMoneyNo());//付款方账号
        motherDTO.setBankId(saveBO.getBankId());//银行id
        motherDTO.setBankName(saveBO.getBankName());//银行名称
        motherDTO.setMoney(saveBO.getMoney());//付款金额
        motherDTO.setType(1);//类型 0余额、1网银
        motherDTO.setStatus(0);//状态 0创建中、1支付中、2成功、3失败、4过期
        motherDTO.setExpiredTime(DateUtils.addMinute(new Date(), 60));

        motherDTO.setNotifyUrl(saveBO.getNotifyUrl());
        motherDTO.setNotifyPageUrl(saveBO.getNotifyPageUrl());
        BigDecimal total = BigDecimalUtils.getBigDecimal(0);
        // 批量支付数据
        for (PayOrderDTO orderDTO : orderDTOS){

            if(StrUtils.isEmpty(orderDTO.getBusinessOrderWaterNo()) || orderDTO.getBusinessType() == null || StrUtils.isEmpty(orderDTO.getTrsFlag())){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            PayUserDTO userDTO = payUserService.getPayUserDTO(orderDTO.getReceiveUserId());
            if(userDTO == null){
                throw new ServiceException(CodeEnum.FAIL_200003);
            }

            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("status", 2);
            wrapper.eq("business_order_water_no", orderDTO.getBusinessOrderWaterNo());
            PayOrderDTO successDto = this.selectOne(wrapper);
            if(successDto != null){
                throw new ServiceException(CodeEnum.FAIL_200023);
            }

            orderDTO.setId(ymlConfig.getPkId());
            orderDTO.setPaymentUserId(motherDTO.getPaymentUserId());
            orderDTO.setPaymentUserName(motherDTO.getPaymentUserName());
            orderDTO.setPaymentUserNo(motherDTO.getPaymentUserNo());
            orderDTO.setReceiveUserId(userDTO.getUserId());
            orderDTO.setReceiveUserName(userDTO.getUserName());
            orderDTO.setReceiveUserNo(userDTO.getZjMoneyNo());
            orderDTO.setStatus(0);
            orderDTO.setType(1);
            orderDTO.setMotherOrderId(motherDTO.getId());
            orderDTO.setNotifyUrl(saveBO.getNotifyUrl());

            total = BigDecimalUtils.add(total, orderDTO.getMoney());

            SplitFundBillInfo quyDak=new SplitFundBillInfo();
            quyDak.setBillinfo_aclamt(BigDecimalUtils.multiply(orderDTO.getMoney(), 100).longValue());//支付金额
            quyDak.setBillinfo_billamt(BigDecimalUtils.multiply(orderDTO.getMoney(), 100).longValue());//订单金额
            quyDak.setBillinfo_billno(orderDTO.getId().toString());//支付单号(唯一)
            quyDak.setBillinfo_goodsmess(orderDTO.getCommodityMsg());//商品信息
            quyDak.setBillinfo_orderno(orderDTO.getBusinessOrderNo());//业务单号
            quyDak.setBillinfo_rcltnm(orderDTO.getReceiveUserName());//收款方户名
            quyDak.setBillinfo_rsubno(orderDTO.getReceiveUserNo());//收款方资金账号
            if(StrUtils.isEmpty(orderDTO.getTrsFlag())){
                orderDTO.setTrsFlag(saveBO.getTrsFlag());
            }
            quyDak.setBillinfo_trsflag(orderDTO.getTrsFlag());//业务标示 A00 入金并支付 B00 收款方收款成功后，再 冻结资金
            quyDak.setBillinfo_usage(orderDTO.getMoneyUsage()+"-"+orderDTO.getId());//资金用途
//                quyDak.setBillinfo_payeefee(MoneyUtil.toNumber(billinfo_payeefee[i]).longValue());//收款方手续费
            billInfolist.add(quyDak);
        }

        if(total.compareTo(motherDTO.getMoney()) != 0){
            throw new ServiceException(CodeEnum.FAIL_200025);
        }
        payOrderMotherService.insert(motherDTO);
        this.insertBatch(orderDTOS);
    }


    public Result httpclientPayOnlineBank(PayOrderMotherSaveBO saveBO, PayOrderMotherDTO motherDTO, List<SplitFundBillInfo> billInfolist, PayHttpLogDTO logDTO) throws Exception {

        /**
         * 2 实例化交易对象
         */
        TrdT4501Request trdRequest = new TrdT4501Request();
        trdRequest.setMsghd_trdt(DateUtils.dateToStr(new Date(),DateUtils.DATE_FORMAT_DATESHORTDAY));// 交易日期
        trdRequest.setSrl_ptnsrl(motherDTO.getId().toString());// 合作方交易流水号
        trdRequest.setCltacc_subno(motherDTO.getPaymentUserNo());//付款方户名:
        trdRequest.setCltacc_cltnm(motherDTO.getPaymentUserName());//付款方资金账号
        trdRequest.setAmt_aclamt(BigDecimalUtils.multiply(motherDTO.getMoney(), 100).longValue());//入金金额:
//            trdRequest.setAmt_payfee(Long.valueOf(amt_payfee));//付款方手续费
        //默认CNY
        trdRequest.setPaytype("2");//支付方式:2：网银 5：快捷支付 6：正扫支付 8：公众号支付 9：银联无卡支付 A:APP 跳转支付 H:H5 跳转支付 L：移动大额支付
        trdRequest.setSecpaytype("1");//支付方式二级分类:1：企业网银 PayType=2 必 输2：个人网银 PayType=2 必 输3：支付宝 PayType=6/8 必 输4：微信 PayType=6/8 必输 5：银联 PayType=6/A/H 必 输8：手机网银 PayType=A/H 必输
        trdRequest.setBankid(motherDTO.getBankId());//付款银行编号
//            trdRequest.setKjbndsrl(kjbndsrl);//原快捷绑卡交易流水号
//            trdRequest.setKjsmsflg(kjsmsflg);//快捷业务是否需要短信确认
//            trdRequest.setSubject(subject);//订单标题
//            trdRequest.setGoodsdesc(goodsdesc);//商品描述
//            trdRequest.setUserid(userid);//用户ID
//            trdRequest.setMinitag(minitag);//小程序标识
//            trdRequest.setAppid(appid);//

        trdRequest.setNotificationurl(saveBO.getNotifyPageUrl());//页面通知URL
        trdRequest.setBillinfoList(billInfolist);
        trdRequest.setReqflg("1");//发送端标记0 手机;1PC 端
        trdRequest.setServnoticurl(noticeUrl);//后台通知url

//            trdRequest.setMerchantid(merchantid);///** 终端商户号 */

        /**
         * 3.报文处理
         */

        trdRequest.process();
        System.out.println("请求报文[" + trdRequest.getRequestPlainText() + "]");
        System.out.println("签名原文[" + trdRequest.getRequestMessage() + "]");
        System.out.println("签名数据[" + trdRequest.getRequestSignature() + "]");
        logDTO.setParams(trdRequest.getRequestPlainText());
        logDTO.setWaterId(motherDTO.getId());

        /**
         * 4 和融资平台通信
         */
        TrdMessenger trdMessenger = new TrdMessenger();
        //responseMessage
        String respMsg = trdMessenger.send(trdRequest);
        TrdT4501Response trdResponse=new TrdT4501Response(respMsg);
        System.out.println("响应报文[" + trdResponse.getResponsePlainText() + "]");

        logDTO.setReturnValue(trdResponse.getResponsePlainText());
        logDTO.setBusinessStatus(trdResponse.getMsghd_rspcode());
        logDTO.setBusinessNotes(trdResponse.getMsghd_rspmsg());
        logDTO.setParams(trdRequest.getRequestPlainText());
        logDTO.setStatus(0);

        if ("000000".equals(trdResponse.getMsghd_rspcode())) {
            // ！！！ 在这里添加合作方处理逻辑！！！
            System.out.println("[msghd_rspmsg]=[" + trdResponse.getMsghd_rspmsg() + "]"); // 返回信息
            System.out.println("[srl_platsrl]=[" + trdResponse.getSrl_platsrl() + "]"); // 平台流水号
            // 支付方式： 2：网银
            String url = URLDecoder.decode(trdResponse.getUrl(), "UTF-8");
            motherDTO.setZjBusinessId(trdResponse.getSrl_platsrl());
            motherDTO.setBankUrl(url);
            return new Result<>();
        } else {
            return new Result(CodeEnum.FAIL_200022.getCode(), trdResponse.getMsghd_rspmsg());
        }

    }


    @Override
    public PayBatchPrintVO printingBatchElectronicReceipt(List<PayBatchPrintBO> list) {
        List<OrderReceiptQuantityVO> orderReceiptQuantityVOArrayList = new ArrayList<>();
        PayBatchPrintVO payBatchPrintVO = new PayBatchPrintVO();
        List<QuyDaT2026> quyDaT2026List = new ArrayList<>();
        List<String> listByOrder = new ArrayList<>();
        for (PayBatchPrintBO payBatchPrintBO : list) {
            List<PayBatchPrintBO> payBatchPrintBOList = new ArrayList<>();
            PayBatchPrintBO payBatchPrintBO2 = new PayBatchPrintBO();
            payBatchPrintBO2.setOrderId(payBatchPrintBO.getOrderId());
            payBatchPrintBO2.setShopId(payBatchPrintBO.getShopId());
            payBatchPrintBO2.setType(1);
            payBatchPrintBOList.add(payBatchPrintBO2);
            PayUserDTO dto = payUserService.getPayUserDTO(Long.parseLong(payBatchPrintBO.getShopId()), 1);
            log.info("---------------dto=="+dto);
            if (dto == null) {
                listByOrder.add(payBatchPrintBO.getOrderId());
                continue;
            }
            EntityWrapper<OrderInfoDTO> orderInfoDTOEntityWrapper = new EntityWrapper<>();
            orderInfoDTOEntityWrapper.eq("order_no",payBatchPrintBO.getOrderId());
            OrderInfoDTO orderInfoDTO = orderInfoService.selectOne(orderInfoDTOEntityWrapper);
            //售后订单
            EntityWrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("order_id",orderInfoDTO.getId());
            wrapper.eq("after_sales_state",3);
            List<OrderReturnCommodityDTO> orderReturnCommodityDTOList = orderReturnCommodityService.selectList(wrapper);

            if (orderReturnCommodityDTOList!=null && orderReturnCommodityDTOList.size()>0){
                for (OrderReturnCommodityDTO orderReturnCommodityDTO : orderReturnCommodityDTOList) {
                    PayBatchPrintBO payBatchPrintBO1 = new PayBatchPrintBO();
                    payBatchPrintBO1.setShopId(payBatchPrintBO.getShopId());
                    payBatchPrintBO1.setType(0);
                    payBatchPrintBO1.setOrderId(String.valueOf(orderReturnCommodityDTO.getId()));
                    payBatchPrintBOList.add(payBatchPrintBO1);
                }
            }

            int num=0;
            OrderReceiptQuantityVO orderReceiptQuantityVO= new OrderReceiptQuantityVO();
            for (PayBatchPrintBO batchPrintBO : payBatchPrintBOList) {
                log.info("请求2014startTime："+new Date());
                TrdT2014Request request2014 = new TrdT2014Request();
                request2014.setCltacc_subno(dto.getZjMoneyNo());
                request2014.setStartnum("1");
                //备注通过orderId过滤转账记录凭证
                request2014.setQptnusg(batchPrintBO.getOrderId());
                TrdMessenger trdMessenger = new TrdMessenger();
                try {
                    request2014.process();
                    String send = trdMessenger.send(request2014);
                    log.info("---------------="+send);
                    log.info("TrdT2014请求明文：" + request2014.getRequestPlainText());
                    TrdT2014Response trdT2014Response = new TrdT2014Response(send);
                    List<QuyDaT2014> quyDatList = trdT2014Response.getQuyDatList();
                    log.info("trdT2014Response电子转账凭证:" + JSON.toJSONString(quyDatList));
                    if (quyDatList != null && quyDatList.size()>0)
                    {
                        for (QuyDaT2014 quyDaT2014 : quyDatList) {
                          //  OrderReceiptQuantityVO orderReceiptQuantityVO= new OrderReceiptQuantityVO();
                            QuyDaT2026 quyDaT2026 = new QuyDaT2026();
                            quyDaT2026.setBillno(quyDaT2014.getBillno());
                            quyDaT2026.setSubno(quyDaT2014.getSubno());
                            quyDaT2026.setVerifycode(quyDaT2014.getVerifycode());
                            quyDaT2026List.add(quyDaT2026);
                        }
                        num=num+quyDatList.size();
                    }else {
                        if (batchPrintBO.getType().equals(1)){
                            listByOrder.add(batchPrintBO.getOrderId());
                        }
                    }
                } catch (Exception e) {
                    log.error("printing electronic receipt error. message is {}", e.getMessage());
                    e.printStackTrace();
                }
            }
                            orderReceiptQuantityVO.setOrderId(payBatchPrintBOList.get(0).getOrderId());
                            orderReceiptQuantityVO.setNum(num);
                            orderReceiptQuantityVOArrayList.add(orderReceiptQuantityVO);

        }

    if (quyDaT2026List!=null && quyDaT2026List.size()>0){
        if (quyDaT2026List.size()>50){
            payBatchPrintVO.setList(orderReceiptQuantityVOArrayList);
            payBatchPrintVO.setType(1);
           return  payBatchPrintVO;
        }else {
            TrdMessenger trdMessenger = new TrdMessenger();
            TrdT2026Request trdT2026Request = new TrdT2026Request();
            try {
                trdT2026Request.setQuydalist(quyDaT2026List);
                trdT2026Request.setSrl_ptnsrl(String.valueOf(ymlConfig.getPkId()));
                trdT2026Request.process();
                log.info("trdT2026请求开始时间：" + new Date());
                log.info("trdT2026请求明文：" + trdT2026Request.getRequestPlainText());
                String response2026 = trdMessenger.send(trdT2026Request);

                log.info("trdT2026请求结束时间：" + new Date());
                TrdT2026Response trdT2026Response = new TrdT2026Response(response2026);
                //log.info("trdT2026响应结果：" + trdT2026Response == null ? "" : trdT2026Response.getPdffile());
                String pdffile = trdT2026Response.getPdffile();
                if (!StrUtils.isEmpty(pdffile)) {
                    byte[] decode = Base64.getDecoder().decode(pdffile);
                    pdffile = new String(decode);
                    log.info("trdT2026响应结果,base64解码后：" + pdffile);
                    payBatchPrintVO.setType(0);
                    payBatchPrintVO.setUrl(pdffile);
                    payBatchPrintVO.setListByOrder(listByOrder);
                }
            }catch (Exception e){
                log.error("printing electronic receipt error. message is {}", e.getMessage());
            }

        }
    }else {
        payBatchPrintVO.setType(2);
        return payBatchPrintVO;
    }
        return payBatchPrintVO;
    }


    private String strUtil(String str){
        Pattern compile = Pattern.compile("[^u4e00-\\u9fa5\\\\\\\\a-zA-Z0-9\\\\\\\\-]");
        Matcher m =compile.matcher(str);
        return m.replaceAll("").trim();
    }
    @Override
    public PayBatchPrintVO printingBatchElectronicReceiptByDetailAdmin(List<PayBatchByRemarksBO> list) {
        List<OrderReceiptQuantityVO> orderReceiptQuantityVOArrayList = new ArrayList<>();
        PayBatchPrintVO payBatchPrintVO = new PayBatchPrintVO();
        List<QuyDaT2026> quyDaT2026List = new ArrayList<>();
        List<String> listByOrder = new ArrayList<>();
        for (PayBatchByRemarksBO payBatchByRemarksBO : list) {
            payBatchByRemarksBO.setRemarks(this.strUtil(payBatchByRemarksBO.getRemarks()));
            PayUserDTO dto = payUserService.getPayUserDTO(Long.parseLong(payBatchByRemarksBO.getShopId()), 3);
            log.info("---------------dto=="+dto);
            if (dto == null) {
                listByOrder.add(payBatchByRemarksBO.getRemarks());
                continue;
            }
            TrdT2014Request request2014 = new TrdT2014Request();
            request2014.setCltacc_subno(dto.getZjMoneyNo());
            request2014.setStartnum("1");
            //备注通过orderId过滤转账记录凭证
            request2014.setQptnusg(payBatchByRemarksBO.getRemarks());
            TrdMessenger trdMessenger = new TrdMessenger();
            try {
                request2014.process();
                String send = trdMessenger.send(request2014);
                log.info("---------------="+send);
                log.info("TrdT2014请求明文：" + request2014.getRequestPlainText());
                TrdT2014Response trdT2014Response = new TrdT2014Response(send);
                List<QuyDaT2014> quyDatList = trdT2014Response.getQuyDatList();
                log.info("trdT2014Response电子转账凭证:" + JSON.toJSONString(quyDatList));
                if (quyDatList != null && quyDatList.size()>0)
                {
                    for (QuyDaT2014 quyDaT2014 : quyDatList) {
                        QuyDaT2026 quyDaT2026 = new QuyDaT2026();
                        quyDaT2026.setBillno(quyDaT2014.getBillno());
                        quyDaT2026.setSubno(quyDaT2014.getSubno());
                        quyDaT2026.setVerifycode(quyDaT2014.getVerifycode());
                        quyDaT2026List.add(quyDaT2026);
                        payBatchPrintVO.setType(0);
                    }
                }else {
                    payBatchPrintVO.setType(2);
                    break;
                }
            } catch (Exception e) {
                log.error("printing electronic receipt error. message is {}", e.getMessage());
                e.printStackTrace();
            }
        }
        if (payBatchPrintVO.getType().equals(2)){
            return payBatchPrintVO;
        }

        if (quyDaT2026List!=null && quyDaT2026List.size()>0){
            if (quyDaT2026List.size()>50){
                payBatchPrintVO.setList(orderReceiptQuantityVOArrayList);
                payBatchPrintVO.setType(1);
                return  payBatchPrintVO;
            }else {
                TrdMessenger trdMessenger = new TrdMessenger();
                TrdT2026Request trdT2026Request = new TrdT2026Request();
                try {
                    trdT2026Request.setQuydalist(quyDaT2026List);
                    trdT2026Request.setSrl_ptnsrl(String.valueOf(ymlConfig.getPkId()));
                    trdT2026Request.process();
                    log.info("trdT2026请求明文：" + trdT2026Request.getRequestPlainText());
                    String response2026 = trdMessenger.send(trdT2026Request);
                    TrdT2026Response trdT2026Response = new TrdT2026Response(response2026);
                      log.info("trdT2026响应明文：" + trdT2026Response.getResponsePlainText());
                    String pdffile = trdT2026Response.getPdffile();
                    if (!StrUtils.isEmpty(pdffile)) {
                        byte[] decode = Base64.getDecoder().decode(pdffile);
                        pdffile = new String(decode);
                        log.info("trdT2026响应结果,base64解码后：" + pdffile);
                        payBatchPrintVO.setType(0);
                        payBatchPrintVO.setUrl(pdffile);
                        payBatchPrintVO.setListByOrder(listByOrder);
                    }
                }catch (Exception e){
                    log.error("printing electronic receipt error. message is {}", e.getMessage());
                }

            }
        }else {
            payBatchPrintVO.setType(2);
            return payBatchPrintVO;
        }
        return payBatchPrintVO;
    }
    @Override
    public PayBatchPrintVO printingBatchElectronicReceiptByDetail(List<PayBatchByRemarksBO> list) {
        List<OrderReceiptQuantityVO> orderReceiptQuantityVOArrayList = new ArrayList<>();
        PayBatchPrintVO payBatchPrintVO = new PayBatchPrintVO();
        List<QuyDaT2026> quyDaT2026List = new ArrayList<>();
        List<String> listByOrder = new ArrayList<>();
        for (PayBatchByRemarksBO payBatchByRemarksBO : list) {
            payBatchByRemarksBO.setRemarks(this.strUtil(payBatchByRemarksBO.getRemarks()));
            PayUserDTO dto = payUserService.getPayUserDTO(Long.parseLong(payBatchByRemarksBO.getShopId()), 1);
            log.info("---------------dto=="+dto);
            if (dto == null) {
                listByOrder.add(payBatchByRemarksBO.getRemarks());
                continue;
            }
                TrdT2014Request request2014 = new TrdT2014Request();
                request2014.setCltacc_subno(dto.getZjMoneyNo());
                request2014.setStartnum("1");
                //备注通过orderId过滤转账记录凭证
                request2014.setQptnusg(payBatchByRemarksBO.getRemarks());
                TrdMessenger trdMessenger = new TrdMessenger();
                try {
                    request2014.process();
                    String send = trdMessenger.send(request2014);
                    log.info("---------------="+send);
                    log.info("TrdT2014请求明文：" + request2014.getRequestPlainText());
                    TrdT2014Response trdT2014Response = new TrdT2014Response(send);
                    List<QuyDaT2014> quyDatList = trdT2014Response.getQuyDatList();
                    log.info("trdT2014Response电子转账凭证:" + JSON.toJSONString(quyDatList));
                    if (quyDatList != null && quyDatList.size()>0)
                    {
                        for (QuyDaT2014 quyDaT2014 : quyDatList) {
                            QuyDaT2026 quyDaT2026 = new QuyDaT2026();
                            quyDaT2026.setBillno(quyDaT2014.getBillno());
                            quyDaT2026.setSubno(quyDaT2014.getSubno());
                            quyDaT2026.setVerifycode(quyDaT2014.getVerifycode());
                            quyDaT2026List.add(quyDaT2026);
                            payBatchPrintVO.setType(0);
                        }
                    }else {
                        payBatchPrintVO.setType(2);
                        break;
                    }
                } catch (Exception e) {
                    log.error("printing electronic receipt error. message is {}", e.getMessage());
                    e.printStackTrace();
                }
        }
        if (payBatchPrintVO.getType().equals(2)){
            return payBatchPrintVO;
        }

        if (quyDaT2026List!=null && quyDaT2026List.size()>0){
            if (quyDaT2026List.size()>50){
                payBatchPrintVO.setList(orderReceiptQuantityVOArrayList);
                payBatchPrintVO.setType(1);
                return  payBatchPrintVO;
            }else {
                TrdMessenger trdMessenger = new TrdMessenger();
                TrdT2026Request trdT2026Request = new TrdT2026Request();
                try {
                    trdT2026Request.setQuydalist(quyDaT2026List);
                    trdT2026Request.setSrl_ptnsrl(String.valueOf(ymlConfig.getPkId()));
                    trdT2026Request.process();
                    log.info("trdT2026请求明文：" + trdT2026Request.getRequestPlainText());
                    String response2026 = trdMessenger.send(trdT2026Request);
                    TrdT2026Response trdT2026Response = new TrdT2026Response(response2026);
                  //  log.info("trdT2026响应明文：" + trdT2026Response.getResponsePlainText());
                    String pdffile = trdT2026Response.getPdffile();
                    if (!StrUtils.isEmpty(pdffile)) {
                        byte[] decode = Base64.getDecoder().decode(pdffile);
                        pdffile = new String(decode);
                        log.info("trdT2026响应结果,base64解码后：" + pdffile);
                        payBatchPrintVO.setType(0);
                        payBatchPrintVO.setUrl(pdffile);
                        payBatchPrintVO.setListByOrder(listByOrder);
                    }
                }catch (Exception e){
                    log.error("printing electronic receipt error. message is {}", e.getMessage());
                }

            }
        }else {
            payBatchPrintVO.setType(2);
            return payBatchPrintVO;
        }
        return payBatchPrintVO;
    }
    @Override
    public PayBatchPrintVO printingSingleElectronicReceiptByDetailAdmin(PayBatchByRemarksBO payBatchByRemarksBO) {
        List<QuyDaT2026> quyDaT2026List = new ArrayList<>();
        PayBatchPrintVO payBatchPrintVO = new PayBatchPrintVO();
        PayUserDTO dto = payUserService.getPayUserDTO(Long.parseLong(payBatchByRemarksBO.getShopId()), 3);
        TrdT2014Request request2014 = new TrdT2014Request();
        request2014.setCltacc_subno(dto.getZjMoneyNo());
        request2014.setStartnum("1");
        //备注通过备注过滤转账记录凭证
        request2014.setQptnusg(strUtil(payBatchByRemarksBO.getRemarks()));
        TrdMessenger trdMessenger = new TrdMessenger();
        try {
            request2014.process();
            String send = trdMessenger.send(request2014);
            log.info("---------------=" + send);
            log.info("TrdT2014请求明文：" + request2014.getRequestPlainText());
            TrdT2014Response trdT2014Response = new TrdT2014Response(send);
            List<QuyDaT2014> quyDatList = trdT2014Response.getQuyDatList();
            log.info("TrdT2014响应明文：" +trdT2014Response.getResponsePlainText());
            log.info("trdT2014Response电子转账凭证:" + JSON.toJSONString(quyDatList));

            if (quyDatList != null && quyDatList.size()>0)
            {
                for (QuyDaT2014 quyDaT2014 : quyDatList) {
                    QuyDaT2026 quyDaT2026 = new QuyDaT2026();
                    quyDaT2026.setBillno(quyDaT2014.getBillno());
                    quyDaT2026.setSubno(quyDaT2014.getSubno());
                    quyDaT2026.setVerifycode(quyDaT2014.getVerifycode());
                    quyDaT2026List.add(quyDaT2026);
                }
            }
            if (quyDaT2026List!=null && quyDaT2026List.size()>0){

                TrdT2026Request trdT2026Request = new TrdT2026Request();
                try {
                    TrdMessenger trdMessenger1 = new TrdMessenger();
                    trdT2026Request.setQuydalist(quyDaT2026List);
                    trdT2026Request.setSrl_ptnsrl(String.valueOf(ymlConfig.getPkId()));
                    trdT2026Request.process();
                    log.info("trdT2026请求明文：" + trdT2026Request.getRequestPlainText());
                    String response2026 = trdMessenger1.send(trdT2026Request);
                    TrdT2026Response trdT2026Response = new TrdT2026Response(response2026);
                    // log.info("trdT2026响应明文：" + trdT2026Response.getResponsePlainText());
                    String pdffile = trdT2026Response.getPdffile();
                    if (!StrUtils.isEmpty(pdffile)) {
                        byte[] decode = Base64.getDecoder().decode(pdffile);
                        pdffile = new String(decode);
                        log.info("trdT2026响应结果,base64解码后：" + pdffile);
                        payBatchPrintVO.setType(0);
                        payBatchPrintVO.setUrl(pdffile);
                    }
                }catch (Exception e){
                    log.error("printing electronic receipt error. message is {}", e.getMessage());
                }
            }else {
                payBatchPrintVO.setType(2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payBatchPrintVO;
    }
    @Override
    public PayBatchPrintVO printingSingleElectronicReceiptByDetail(PayBatchByRemarksBO payBatchByRemarksBO) {
        List<QuyDaT2026> quyDaT2026List = new ArrayList<>();
        PayBatchPrintVO payBatchPrintVO = new PayBatchPrintVO();
        PayUserDTO dto = payUserService.getPayUserDTO(Long.parseLong(payBatchByRemarksBO.getShopId()), 1);
        TrdT2014Request request2014 = new TrdT2014Request();
        request2014.setCltacc_subno(dto.getZjMoneyNo());
        request2014.setStartnum("1");
        //备注通过备注过滤转账记录凭证
        request2014.setQptnusg(strUtil(payBatchByRemarksBO.getRemarks()));
        TrdMessenger trdMessenger = new TrdMessenger();
        try {
            request2014.process();
            String send = trdMessenger.send(request2014);
            log.info("---------------=" + send);
            log.info("TrdT2014请求明文：" + request2014.getRequestPlainText());
            TrdT2014Response trdT2014Response = new TrdT2014Response(send);
            List<QuyDaT2014> quyDatList = trdT2014Response.getQuyDatList();
            log.info("TrdT2014响应明文：" +trdT2014Response.getResponsePlainText());
            log.info("trdT2014Response电子转账凭证:" + JSON.toJSONString(quyDatList));

            if (quyDatList != null && quyDatList.size()>0)
            {
                for (QuyDaT2014 quyDaT2014 : quyDatList) {
                    QuyDaT2026 quyDaT2026 = new QuyDaT2026();
                    quyDaT2026.setBillno(quyDaT2014.getBillno());
                    quyDaT2026.setSubno(quyDaT2014.getSubno());
                    quyDaT2026.setVerifycode(quyDaT2014.getVerifycode());
                    quyDaT2026List.add(quyDaT2026);
                }
            }
            if (quyDaT2026List!=null && quyDaT2026List.size()>0){

                    TrdT2026Request trdT2026Request = new TrdT2026Request();
                    try {
                        TrdMessenger trdMessenger1 = new TrdMessenger();
                        trdT2026Request.setQuydalist(quyDaT2026List);
                        trdT2026Request.setSrl_ptnsrl(String.valueOf(ymlConfig.getPkId()));
                        trdT2026Request.process();
                        log.info("trdT2026请求明文：" + trdT2026Request.getRequestPlainText());
                        String response2026 = trdMessenger1.send(trdT2026Request);
                        TrdT2026Response trdT2026Response = new TrdT2026Response(response2026);
                       // log.info("trdT2026响应明文：" + trdT2026Response.getResponsePlainText());
                        String pdffile = trdT2026Response.getPdffile();
                        if (!StrUtils.isEmpty(pdffile)) {
                            byte[] decode = Base64.getDecoder().decode(pdffile);
                            pdffile = new String(decode);
                            log.info("trdT2026响应结果,base64解码后：" + pdffile);
                            payBatchPrintVO.setType(0);
                            payBatchPrintVO.setUrl(pdffile);
                        }
                    }catch (Exception e){
                        log.error("printing electronic receipt error. message is {}", e.getMessage());
                    }
            }else {
                payBatchPrintVO.setType(2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payBatchPrintVO;
    }
    }
